package com.lyf.Dao.Impl;

import com.lyf.Dao.EmployeeDao;
import com.lyf.Entity.Employee;
import org.hibernate.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Repository
@Transactional//开启事务
public class EmployeeDaoImpl implements EmployeeDao {
    @Autowired
    private SessionFactory SessionFactory;
    private Logger logger = LoggerFactory.getLogger(EmployeeDaoImpl.class);
    /*
    * 添加
    * */
    @Override
    public int AddEmployee(Employee employee) {
        try {
            Session session =SessionFactory.openSession();
            int ID = (int) session.save(employee);
            return ID;
        }catch (Exception ex){
            logger.error(ex.getMessage());
        }
        return 0;
    }

    /*
    * 查询全部
    * */
    @Override
    public List<Employee> EmployeeList() {
        try {
            String hql = "from Employee";
            Query query = SessionFactory.getCurrentSession().createQuery(hql);
            return query.list();
        }catch (Exception ex){
            logger.error(ex.getMessage());
        }
        return null;
    }

    /*
    * 修改(地址和设置修改时间)
    * */
    @Override
    public int UpdateEmployee(Employee employee) {
        try {
            Session session =SessionFactory.openSession();
            String hql = "UPDATE Employee set updateTime= :UpdateTime,address = :Address "  +
                    "WHERE ID = :Id";
            Query query = session.createQuery(hql);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            query.setParameter("UpdateTime", df.format(new Date()));// new Date()为获取当前系统时间
            query.setParameter("Address", employee.getAddress());
            query.setParameter("Id", employee.getId());
            int result = query.executeUpdate();
            return  result;
        }catch (Exception ex){
            logger.error(ex.getMessage());
        }
        return 0;
    }
    /*
    * 删除
    * */
    @Override
    public int DeleteEmployee(Employee employee) {
        try {
            Session session =SessionFactory.openSession();
            String hql = "DELETE FROM Employee "  +
                    "WHERE ID = :employee_id";
            Query query = session.createQuery(hql);
            query.setParameter("employee_id", employee.getId());
            int result = query.executeUpdate();
            return result;
        }catch (Exception ex){
            logger.error(ex.getMessage());
        }
        return 0;
    }
}
